<template>
  <div class="app-container">
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="queryParams.keyword"
            placeholder="订单号/会员名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="订单状态" clearable>
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.payment_type" placeholder="支付方式" clearable>
            <el-option label="黑卡支付" value="black_card" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wechat" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="order_no" label="订单号" width="180" />
        <el-table-column prop="member_name" label="会员名称" width="120" />
        <el-table-column prop="product_name" label="商品名称" width="200" />
        <el-table-column prop="amount" label="订单金额" width="120">
          <template #default="scope">
            {{ scope.row.amount / 100 }}
          </template>
        </el-table-column>
        <el-table-column prop="payment_type" label="支付方式" width="120">
          <template #default="scope">
            {{ getPaymentTypeName(scope.row.payment_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payment_time" label="支付时间" width="180" />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              v-if="scope.row.status === 'paid'"
              type="danger"
              link
              @click="handleRefund(scope.row)"
            >
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 退款弹窗 -->
    <el-dialog
      title="退款"
      v-model="refundDialog.visible"
      width="500px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundDialog.form"
        :rules="refundDialog.rules"
        label-width="100px"
      >
        <el-form-item label="订单号">
          <span>{{ refundDialog.form.order_no }}</span>
        </el-form-item>
        <el-form-item label="商品名称">
          <span>{{ refundDialog.form.product_name }}</span>
        </el-form-item>
        <el-form-item label="订单金额">
          <span>{{ refundDialog.form.amount / 100 }}</span>
        </el-form-item>
        <el-form-item label="支付方式">
          <span>{{ getPaymentTypeName(refundDialog.form.payment_type) }}</span>
        </el-form-item>
        <el-form-item label="退款金额" prop="refund_amount">
          <el-input-number
            v-model="refundDialog.form.refund_amount"
            :min="0"
            :max="refundDialog.form.amount"
            :precision="2"
            :step="100"
          />
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input
            v-model="refundDialog.form.reason"
            type="textarea"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialog.visible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitRefund"
            :loading="refundDialog.loading"
          >
            确认退款
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: '',
  status: '',
  payment_type: '',
  dateRange: []
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 支付方式字典
const paymentTypeDict = {
  black_card: '黑卡支付',
  alipay: '支付宝',
  wechat: '微信支付'
}

// 状态字典
const statusDict = {
  pending: { name: '待支付', type: 'warning' },
  paid: { name: '已支付', type: 'success' },
  cancelled: { name: '已取消', type: 'info' },
  refunded: { name: '已退款', type: 'danger' }
}

// 获取支付方式名称
const getPaymentTypeName = (type) => {
  return paymentTypeDict[type] || type
}

// 获取状态名称
const getStatusName = (status) => {
  return statusDict[status]?.name || status
}

// 获取状态类型
const getStatusType = (status) => {
  return statusDict[status]?.type || ''
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      start_date: queryParams.dateRange?.[0],
      end_date: queryParams.dateRange?.[1]
    }
    delete params.dateRange
    
    const res = await request.get('/admin/order/consume/list', { params })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取列表失败：', error)
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.status = ''
  queryParams.payment_type = ''
  queryParams.dateRange = []
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 详情
const handleDetail = (row) => {
  ElMessage.info('详情功能开发中')
}

// 退款弹窗
const refundDialog = reactive({
  visible: false,
  loading: false,
  form: {
    order_no: '',
    product_name: '',
    amount: 0,
    payment_type: '',
    refund_amount: 0,
    reason: ''
  },
  rules: {
    refund_amount: [
      { required: true, message: '请输入退款金额', trigger: 'blur' },
      { type: 'number', min: 0.01, message: '退款金额必须大于0', trigger: 'blur' }
    ],
    reason: [
      { required: true, message: '请输入退款原因', trigger: 'blur' }
    ]
  }
})

const refundFormRef = ref(null)

// 打开退款弹窗
const handleRefund = (row) => {
  refundDialog.form.order_no = row.order_no
  refundDialog.form.product_name = row.product_name
  refundDialog.form.amount = row.amount
  refundDialog.form.payment_type = row.payment_type
  refundDialog.form.refund_amount = row.amount
  refundDialog.visible = true
}

// 提交退款
const submitRefund = async () => {
  if (!refundFormRef.value) return
  await refundFormRef.value.validate(async (valid) => {
    if (valid) {
      refundDialog.loading = true
      try {
        const res = await request.post('/admin/order/consume/refund', refundDialog.form)
        ElMessage.success('退款申请提交成功')
        refundDialog.visible = false
        getList()
      } catch (error) {
        console.error('退款申请提交失败：', error)
      }
      refundDialog.loading = false
    }
  })
}

// 初始化
getList()
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .table-wrapper {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 